#include<bits/stdc++.h>
#define sd(n) scanf("%d",&n) 
#define sld(n) scanf("%lld",&n)
#define pd(n) printf("%d", (n))
#define pld(n) printf("%lld", n)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define fi first
#define se second
//const int N=2e5;
#define INF 0x7fffffff
typedef long long int ll;
using namespace std;
//----------------------------------------------------------------------------//
int dx[] = {-1,1,0,0};int dy[] = {0,0,-1,1};
const int N = 510; 
typedef pair<int, int> PII;
int n, m,x1,y1,x2,y2;
int x_d,y_d,x_k,y_k;
char g[N][N];//存放地图
int d[N][N];//存每一个点到起点的距离
PII q[N * N];
int bfs(int&sx,int&sy,int&ex,int&ey)
{
    int hh = 0, tt = 0;
    q[0] = {sx,sy};

    memset(d, - 1, sizeof d);

    bool ok=false;
    d[sx][sy] = 0;
    while(hh <= tt)
    {
        PII t = q[hh ++ ];

        for(int i = 0; i < 4; i ++ )
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if(x >= 0 && x < n && y >= 0 && y < m && (g[x][y] == '.'||g[x][y]=='K') && d[x][y] == -1)
            {
                d[x][y] = d[t.first][t.second] + 1;
                q[ ++ tt ] = {x, y};
                if(x==ex&&y==ey) goto ed;
            }
        }
    }
    ed:;
    return d[ex][ey];
}

int main()
{
	sd(n);sd(m);
    for(int i = 0; i < n; i ++ )
        for(int j = 0; j < m; j ++ )
         {
         	cin >> g[i][j];
         	if(g[i][j]=='S') x1=i,y1=j;
         	if(g[i][j]=='E') x2=i,y2=j;
         	if(g[i][j]=='D') x_d=i,y_d=j;
         	if(g[i][j]=='K') x_k=i,x_k=j;
         }
     //直接过
     int ans=bfs(x1,y1,x2,y2);
     
     //找k,由于我开始有判断退出这一步,所以我这里要重新bfs,如果没有判断退出走完整张图会过于大
     int ans_k=bfs(x1,y1,x_d,y_d);
     if(ans_k==-1)
     {
     	pd(-1);puts("");return 0;
     }
     //k找d
     int ans_d=bfs(x_k,y_k,x_d,y_d);
     if(ans_d==-1)
     {
     	pd(-1);puts("");return 0;
     }

     //更新d
     g[x_d][y_d]='.';

     int ans_e=bfs(x_d,y_d,x2,y2);
     if(ans_e==-1)
     {
     	pd(-1);puts("");return 0;
     }

     if(ans!=0)
     {
     	int res=min(ans,ans_k+ans_d+ans_e);
     	pd(ans);puts("");
     }


    

	return 0;
}